<template>
  <div class="group-manage">
    <!-- 返回按钮 -->
    <div class="back-button" @click="goBack">
      <i class="fas fa-arrow-left"></i>
      <span>返回小组详情</span>
    </div>

    <div class="main-content">
      <!-- 小组头部信息 -->
      <div class="group-header">
        <div v-if="loading.group" class="loading-container">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>
        <template v-else>
          <div class="group-basic-info">
            <div class="group-name-circle large">{{ group.name }}</div>
            <div class="group-title">
              <h1>{{ group.name }} <span class="manage-badge">管理</span></h1>
              <div class="group-stats">
                <span><i class="fas fa-users"></i> {{ group.memberCount || 0 }}名成员</span>
                <span><i class="fas fa-code"></i> {{ group.problemCount || 0 }}道题目</span>
              </div>
            </div>
          </div>
          <div class="group-actions">
            <button class="edit-btn" @click="showEditGroupDialog">
              <i class="fas fa-edit"></i> 编辑小组
            </button>
          </div>
        </template>
      </div>

      <!-- 导航标签页 -->
      <div class="nav-tabs">
        <button 
          v-for="tab in tabs" 
          :key="tab.key"
          :class="['tab-btn', { active: currentTab === tab.key }]"
          @click="currentTab = tab.key"
        >
          <i :class="tab.icon"></i> {{ tab.name }}
        </button>
      </div>

      <!-- 内容区域 -->
      <div class="tab-content">
        <!-- 成员管理 -->
        <div v-if="currentTab === 'members'" class="members-management">
          <div class="content-header">
            <h2>成员管理</h2>
            <div class="search-box">
              <i class="fas fa-search"></i>
              <input type="text" placeholder="搜索成员..." v-model="memberSearch">
            </div>
          </div>
          
          <div v-if="loading.members" class="loading-container">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
          </div>
          <div v-else-if="members.length === 0" class="empty-state">
            <i class="fas fa-users"></i>
            <p>暂无成员</p>
          </div>
          <div v-else class="member-items">
            <div v-for="member in filteredMembers" :key="member.id" class="member-item">
              <img :src="member.avatar" :alt="member.name" class="member-avatar">
              <div class="member-info">
                <h3>{{ member.name }}</h3>
                <span class="member-role" :class="member.role">
                  {{ getRoleText(member.role) }}
                </span>
              </div>
              <div class="member-actions" v-if="member.userId !== userId">
                <button class="remove-btn" @click="confirmRemoveMember(member)">
                  <i class="fas fa-user-minus"></i> 移除
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 加入申请 -->
        <div v-if="currentTab === 'applications'" class="applications-management">
          <div class="content-header">
            <h2>加入申请</h2>
          </div>
          
          <div v-if="loading.applications" class="loading-container">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
          </div>
          <div v-else-if="pendingMembers.length === 0" class="empty-state">
            <i class="fas fa-user-clock"></i>
            <p>暂无待审核的加入申请</p>
          </div>
          <div v-else class="application-items">
            <div v-for="member in pendingMembers" :key="member.id" class="application-item">
              <img :src="member.avatar" :alt="member.name" class="member-avatar">
              <div class="member-info">
                <h3>{{ member.name }}</h3>
                <span class="application-time">申请时间：{{ member.joinTime }}</span>
              </div>
              <div class="application-actions">
                <button class="approve-btn" @click="approveJoinRequest(member)">
                  <i class="fas fa-check"></i> 批准
                </button>
                <button class="reject-btn" @click="rejectJoinRequest(member)">
                  <i class="fas fa-times"></i> 拒绝
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 小组设置 -->
        <div v-if="currentTab === 'settings'" class="group-settings">
          <div class="content-header">
            <h2>小组设置</h2>
          </div>
          
          <div class="settings-form">
            <div class="form-group">
              <label>小组名称</label>
              <input type="text" v-model="groupSettings.name" placeholder="请输入小组名称">
            </div>
            <div class="form-group">
              <label>小组描述</label>
              <textarea 
                v-model="groupSettings.description" 
                placeholder="请输入小组描述"
                rows="4"
              ></textarea>
            </div>
            <div class="form-actions">
              <button class="save-btn" @click="saveGroupSettings">
                <i class="fas fa-save"></i> 保存设置
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 确认对话框 -->
    <div class="dialog-overlay" v-if="showConfirmDialog" @click="showConfirmDialog = false">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h2>{{ confirmDialogTitle }}</h2>
          <button class="close-btn" @click="showConfirmDialog = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <p>{{ confirmDialogMessage }}</p>
          <div class="dialog-actions">
            <button class="cancel-btn" @click="showConfirmDialog = false">
              取消
            </button>
            <button class="confirm-btn" @click="confirmAction">
              确认
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { groupApi } from '@/utils/api.js'
import { generateGroupAvatar } from '@/utils/helpers.js'

export default {
  name: 'GroupManageView',
  data() {
    return {
      currentTab: 'members',
      memberSearch: '',
      tabs: [
        { key: 'members', name: '成员管理', icon: 'fas fa-users' },
        { key: 'applications', name: '加入申请', icon: 'fas fa-user-clock' },
        { key: 'settings', name: '小组设置', icon: 'fas fa-cog' }
      ],
      group: {},
      members: [],
      pendingMembers: [],
      loading: {
        group: false,
        members: false,
        applications: false
      },
      userId: null, // 当前用户ID
      groupId: null, // 当前小组ID
      
      // 小组设置
      groupSettings: {
        name: '',
        description: ''
      },
      
      // 确认对话框
      showConfirmDialog: false,
      confirmDialogTitle: '',
      confirmDialogMessage: '',
      confirmAction: null,
      targetMember: null
    }
  },
  computed: {
    filteredMembers() {
      return this.members.filter(member => 
        member.name && member.name.toLowerCase().includes(this.memberSearch.toLowerCase())
      )
    }
  },
  created() {
    // 从路由参数获取小组ID
    this.groupId = parseInt(this.$route.params.id);
    // 假设从登录状态或存储中获取用户ID
    this.userId = localStorage.getItem('userId') || 1;
    
    // 加载小组数据
    this.fetchGroupData();
    this.fetchGroupMembers();
    this.fetchPendingMembers();
  },
  methods: {
    // 获取小组基本信息
    async fetchGroupData() {
      this.loading.group = true;
      try {
        const response = await groupApi.getGroupDetail(this.groupId);
        if (response.result === 'success') {
          this.group = {
            ...response.group,
            avatar: generateGroupAvatar(response.group.name)
          };
          
          // 初始化小组设置
          this.groupSettings.name = this.group.name;
          this.groupSettings.description = this.group.description;
        } else {
          console.error('获取小组详情失败:', response.message);
        }
      } catch (error) {
        console.error('获取小组详情出错:', error);
      } finally {
        this.loading.group = false;
      }
    },
    
    // 获取小组成员列表
    async fetchGroupMembers() {
      this.loading.members = true;
      try {
        const response = await groupApi.getGroupMembers(this.groupId);
        if (response.result === 'success' && response.members) {
          this.members = response.members
            .filter(member => member.status === 'approved')
            .map(member => ({
              id: member.id,
              userId: member.user_id,
              name: member.username,
              avatar: member.avatar || generateGroupAvatar(member.username),
              role: member.role
            }));
        } else {
          console.error('获取小组成员失败:', response.message);
          this.members = []; // 初始化为空数组
        }
      } catch (error) {
        console.error('获取小组成员出错:', error);
        this.members = []; // 出错时初始化为空数组
      } finally {
        this.loading.members = false;
      }
    },
    
    // 获取待审核成员列表
    async fetchPendingMembers() {
      this.loading.applications = true;
      try {
        const response = await groupApi.getPendingMembers(this.groupId);
        if (response.result === 'success') {
          if (response.members) {
            this.pendingMembers = response.members.map(member => ({
              id: member.id,
              userId: member.user_id,
              name: member.username,
              avatar: generateGroupAvatar(member.username), // 使用用户名生成头像
              joinTime: member.join_time
            }));
          } else {
            this.pendingMembers = []; // 如果没有待审核成员，设置为空数组
          }
        } else {
          console.error('获取待审核成员失败:', response.message);
          this.pendingMembers = []; // 初始化为空数组
        }
      } catch (error) {
        console.error('获取待审核成员出错:', error);
        this.pendingMembers = []; // 出错时初始化为空数组
      } finally {
        this.loading.applications = false;
      }
    },
    
    // 批准加入申请
    async approveJoinRequest(member) {
      try {
        const response = await groupApi.approveJoin(this.groupId, member.userId, this.userId);
        if (response.result === 'success') {
          // 从待审核列表中移除
          this.pendingMembers = this.pendingMembers.filter(m => m.id !== member.id);
          // 刷新成员列表
          this.fetchGroupMembers();
        } else {
          console.error('批准加入申请失败:', response.message);
        }
      } catch (error) {
        console.error('批准加入申请出错:', error);
      }
    },
    
    // 拒绝加入申请
    async rejectJoinRequest(member) {
      try {
        const response = await groupApi.rejectJoin(this.groupId, member.userId, this.userId);
        if (response.result === 'success') {
          // 从待审核列表中移除
          this.pendingMembers = this.pendingMembers.filter(m => m.id !== member.id);
        } else {
          console.error('拒绝加入申请失败:', response.message);
        }
      } catch (error) {
        console.error('拒绝加入申请出错:', error);
      }
    },
    
    // 确认移除成员
    confirmRemoveMember(member) {
      this.targetMember = member;
      this.confirmDialogTitle = '移除成员';
      this.confirmDialogMessage = `确定要将 ${member.name} 从小组中移除吗？`;
      this.confirmAction = this.removeMember;
      this.showConfirmDialog = true;
    },
    
    // 移除成员
    async removeMember() {
      if (!this.targetMember) return;
      
      try {
        const response = await groupApi.removeMember(
          this.groupId, 
          this.targetMember.userId, 
          this.userId
        );
        
        if (response.result === 'success') {
          // 从成员列表中移除
          this.members = this.members.filter(m => m.id !== this.targetMember.id);
          this.showConfirmDialog = false;
        } else {
          console.error('移除成员失败:', response.message);
        }
      } catch (error) {
        console.error('移除成员出错:', error);
      }
    },
    
    // 显示编辑小组对话框
    showEditGroupDialog() {
      this.currentTab = 'settings';
    },
    
    // 保存小组设置
    async saveGroupSettings() {
      try {
        const data = {
          id: this.groupId,
          name: this.groupSettings.name,
          description: this.groupSettings.description,
          status: 1
        };
        
        const response = await groupApi.updateGroup(data);
        if (response.result === 'success') {
          // 更新小组信息
          this.group.name = this.groupSettings.name;
          this.group.description = this.groupSettings.description;
          this.group.avatar = generateGroupAvatar(this.groupSettings.name);
        } else {
          console.error('更新小组设置失败:', response.message);
        }
      } catch (error) {
        console.error('更新小组设置出错:', error);
      }
    },
    
    getRoleText(role) {
      const roles = {
        admin: '管理员',
        member: '成员'
      }
      return roles[role] || '成员'
    },
    
    goBack() {
      this.$router.push(`/group/${this.groupId}`)
    }
  }
}
</script>

<style scoped>
.group-manage {
  min-height: 100vh;
  background: #f0f7ff;
  padding: 60px 20px 20px; /* 为返回按钮留出空间 */
  position: relative; /* 用于返回按钮定位 */
}

.main-content {
  max-width: 1200px; /* 添加最大宽度 */
  margin: 0 auto; /* 居中显示 */
}

/* 返回按钮样式 */
.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  padding: 8px 16px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: #4a5568;
  transition: all 0.3s ease;
  z-index: 100;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.back-button:hover {
  background: #f8fafd;
  transform: translateY(-1px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.group-header {
  background: white;
  border-radius: 10px;
  padding: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
}

.group-basic-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.group-name-circle {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: #3498db;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  padding: 8px;
  text-align: center;
  word-break: break-all;
  line-height: 1.2;
}

.group-name-circle.large {
  width: 80px;
  height: 80px;
  font-size: 18px;
}

.group-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.group-title h1 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 12px;
}

.manage-badge {
  font-size: 14px;
  padding: 2px 8px;
  background: #fdf6ec;
  color: #e6a23c;
  border-radius: 4px;
}

.group-stats {
  display: flex;
  gap: 16px;
  color: #5b7b9a;
}

.edit-btn {
  padding: 8px 16px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.nav-tabs {
  background: white;
  border-radius: 10px;
  padding: 12px;
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
}

.tab-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  background: transparent;
  color: #5b7b9a;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tab-btn.active {
  background: #3498db;
  color: white;
}

.tab-content {
  background: white;
  border-radius: 10px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #5b7b9a;
}

.search-box input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid #e8f4ff;
  border-radius: 6px;
  font-size: 14px;
}

/* 成员列表样式 */
.member-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.member-item {
  background: #f8faff;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.member-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.member-info {
  flex: 1;
}

.member-info h3 {
  margin: 0 0 4px 0;
  color: #2c3e50;
}

.member-role {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.member-role.admin {
  background: #fdf6ec;
  color: #e6a23c;
}

.member-actions {
  display: flex;
  gap: 8px;
}

.remove-btn {
  padding: 6px 12px;
  background: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 申请列表样式 */
.application-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.application-item {
  background: #f8faff;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.application-time {
  font-size: 14px;
  color: #5b7b9a;
}

.application-actions {
  display: flex;
  gap: 8px;
}

.approve-btn {
  padding: 6px 12px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}

.reject-btn {
  padding: 6px 12px;
  background: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 设置表单样式 */
.settings-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  color: #2c3e50;
  font-weight: 500;
}

.form-group input,
.form-group textarea {
  padding: 8px 12px;
  border: 1px solid #e8f4ff;
  border-radius: 6px;
  font-size: 14px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
}

.save-btn {
  padding: 8px 16px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 确认对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  border-radius: 10px;
  width: 90%;
  max-width: 400px;
  overflow: hidden;
}

.dialog-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e8f4ff;
}

.dialog-header h2 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  color: #5b7b9a;
  cursor: pointer;
  font-size: 18px;
}

.dialog-body {
  padding: 16px;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
}

.cancel-btn {
  padding: 8px 16px;
  background: #f8faff;
  color: #5b7b9a;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.confirm-btn {
  padding: 8px 16px;
  background: #f56c6c;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #3498db;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 20px;
  text-align: center;
}

.empty-state i {
  font-size: 48px;
  color: #5b7b9a;
}

.empty-state p {
  color: #5b7b9a;
  margin: 0;
}
</style> 